//
//  WebSocket.swift
//  PerfectTemplate
//
//  Created by yaqiang bi on 2017/5/4.
//
//

import PerfectLib
import PerfectHTTP
import PerfectWebSockets

class EchoHandle: WebSocketSessionHandler {
    let socketProtocol: String? = "echo"
    func handleSession(request: HTTPRequest, socket: WebSocket) {
        socket.readStringMessage { (string, op, fin) in
            guard string != nil else{
                print("3这里调用了")
                socket.close()
                return
            }
            print("已经获取了信息:\(String(describing: string))\t操作码：\(op)\t是否全部读取\(fin)")
            socket.sendStringMessage(string: string!, final: true, completion: {
                self.handleSession(request: request, socket: socket)
            })
            
        }
    }
}

func webSocket()->Route{
    let route = Route(method: .get, uri:"/echo") { (request, response) in
        WebSocketHandler(handlerProducer: { (request, protocols) -> WebSocketSessionHandler? in
            guard protocols.contains("echo") else{
                return nil
            }
            print("1这里调用了")
            return EchoHandle()
        }).handleRequest(request: request, response: response)
        
        print("2这里调用了")
    }
    return route
}
